package tech.heptagram.staff.config.handler;

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Rest 请求默认异常处理
 * Created by fengqiang on 2017/6/15.
 */
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {

    private static final Charset DEFAULT_CHARSET = Charset.forName("Utf8");

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return super.hasError(response);
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        HttpStatus statusCode = getHttpStatusCode(response);
        switch (statusCode.series()) {
            case CLIENT_ERROR:
                throw new HttpClientErrorException(statusCode, response.getStatusText(),
                        response.getHeaders(), getResponseBody(response), getCharset(response));
            case SERVER_ERROR:
                return;
            default:
                throw new RestClientException("Unknown status code [" + statusCode + "]");
        }
    }
}
